//
//  StatusViewModel.swift
//  XLWB
//
//  Created by 郭亮 on 16/3/17.
//  Copyright © 2016年 gl. All rights reserved.
//

import UIKit

class StatusViewModel: NSObject {
    // MARK:-属性
    /// 数据模型属性
    var status: Status?
    /// 来源字符串
    var sourceText: String?
    /// 认证显示的图标
    var verifiedImage : UIImage?
    /// 会员显示的图标
    var vipImage : UIImage?
    /// 显示时间
    var display_at: String? {
        guard let create = status?.created_at else {
            return ""
        }
        return NSDate.createTimeString(create)
    }
    /// 头像的url
    var iconUrl: NSURL? {
        guard let urlString = status?.user?.profile_image_url else {
        return NSURL(string: "")
        }
        return NSURL(string: urlString)
    }
    /// 微博配图URL
    var pictureUrls: [NSURL] = [NSURL]()
    
    /// 转发微博文本
    var retweetedText: String?
    
    // MARK:-自定义构造方法
    init(status: Status) {
        super.init()
        self.status = status
        // 来源字符串
        if let source = status.source where status.source != "" {
            let startIndex = (source as NSString).rangeOfString(">").location + 1
            let length = (source as NSString).rangeOfString("</").location - startIndex
            sourceText = "来自 " + (source as NSString).substringWithRange(NSRange(location: startIndex, length: length))
        }
        // 会员等级
        let mbrank = status.user?.mbrank ?? 0
        if  mbrank >= 1 && mbrank <= 6 {
            // 1.拼接会员图片名称
            let vipImageName = "common_icon_membership_level\(mbrank)"
            
            // 2.设置会员图片
            vipImage = UIImage(named: vipImageName)
        } else {
            vipImage = nil
        }
        // 认证图标
        let type = status.user?.verified_type ?? -1
        switch type {
        case 0:
            verifiedImage = UIImage(named: "avatar_vip")
        case 2, 3, 5:
            verifiedImage = UIImage(named: "avatar_enterprise_vip")
        case 220:
            verifiedImage = UIImage(named: "avatar_grassroot")
        default:
            verifiedImage = nil
        }
        // 微博配图
        let urlStringDicts = status.retweeted_status != nil ? status.retweeted_status?.pic_urls : status.pic_urls
        if let urlStringDicts = urlStringDicts {
            for urlStringDict in urlStringDicts {
            let urlString = urlStringDict["thumbnail_pic"] as? String
                let url = NSURL(string: urlString ?? "")
                pictureUrls.append(url!)
            }
        }
        // 转发微博文本
        if let retweedStatus = status.retweeted_status {
            retweetedText = retweedStatus.text
        }else {
        retweetedText = nil
        }
    }
    
}
